<template>
  <common-search :show-item="2" :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" v-model="query" :formItems="formItems" @search="search" @reset="reset"></common-search>
  <a-button type="primary" @click="add" v-modulePerm="['trackUploading:add']">
    <template #icon>
      <PlusOutlined />
    </template>
    新增
  </a-button>
  <a-button type="primary" style="margin-left: 15px;" @click="imports" :loading="importLoading" v-modulePerm="['trackUploading:import']">
    <template #icon>
      <ExportOutlined />
    </template>
    导入
  </a-button>
<!--  <a-button type="primary" style="margin-left: 15px;" @click="exports" :loading="exportLoading" v-modulePerm="['trackUploading:export']">-->
<!--    <template #icon>-->
<!--      <ExportOutlined />-->
<!--    </template>-->
<!--    导出-->
<!--  </a-button>-->
  <!--  <a-button type="primary" @click="openSuperSearch = true" style="margin-left: 20px;">-->
  <!--    <template #icon>-->
  <!--      <HeartFilled />-->
  <!--    </template>-->
  <!--    高级查询-->
  <!--  </a-button>-->
<!--  <my-alert @onClearSelected="onClearSelected" :selectedRowKeys="selectedRowKeys" style="margin-top: 10px;">-->
<!--    <template #setting>-->
<!--      <columns-check-box :columns="columns" :name="'trackList'" v-model:checkedList="checkedList" v-model:filter-columns="filterColumns"/>-->
<!--    </template>-->
<!--  </my-alert>-->
  <common-table
      :customFilterDropdown="true"
      :columns="filterColumns"
      :dataSource="dataList"
      v-model:localPagination="page"
      @paginationChange="onPageChange"
      v-model:loading="loading"
      :rowKey="(record) => record.id"
      :scroll="{ x: 'max-content'}"
      :slots="['action']"
  >
    <template #action="{ record }">
      <a-dropdown>
        <a @click.prevent>更多 <DownOutlined /></a>
        <template #overlay>
          <a-menu>
            <a-menu-item>
              <a @click="handleDetail(record)">详情</a>
            </a-menu-item>
            <a-menu-item v-if="modulePerm(['trackUploading:delete'])">
              <a-popconfirm
                  title="是否要删除？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="handleDel(record)"
                  @cancel="cancel"
              >
                <a>删除</a>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </template>
  </common-table>
  <super-search :columns="columns" :openSuperSearch="openSuperSearch" @close="closeSuperSearch"/>
  <upload-file :type="'commPost'" :url="'/tms/tracking/status/import'"  :method="'post'" :title="'导入'" ref="upFile" :name="'轨迹上传'" @search="search">
    <template #template>
      <a @click="downLoadTemplate">下载模版</a>
    </template>
  </upload-file>
  <EditForm :showDetail="showDetail" :edit-form="editForm" :rules="addRules" :form-item="formItem" @close="closeEdit" @submit="submitEdit" :record="baseData"/>
  <AddForm :add-form="addForm" :rules="addRules" @close="closeAdd" :form-item="addFormItem" @submit="submitAdd"/>
</template>
<script>
export default {
  name:"upload-trackUploading"
}
</script>
<script setup>
import CommonSearch from "@/components/commonSearch/index.vue";
import CommonTable from "@/components/commonTable/index.vue";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import {ref,onMounted} from "vue";
import {message} from "ant-design-vue";
import {postFile} from "@utils/service/index.js";
import {getManyDictItems} from "@/api/system/dict.js";
import SuperSearch from "@/components/modal/superSearch.vue";
import MyAlert from "@/components/alert/my-alert.vue";
import ColumnsCheckBox from "@/components/popconfirm/columnsCheckBox.vue";
import {getLVal} from "@utils/storage.js";
import {modulePerm} from "@utils/modulePerm.js";
import AddForm from "@/views/upload/components/addForm.vue";
import EditForm from "@/views/upload/components/editForm.vue";
import {deleteOne} from "@/api/system/index.js";
import {addTracking, editTracking, getTrackingPage} from "@/api/upload/trackUploading.js";
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getTrackingPage,
  queryFactory: () => ({
    columns:'createTime',
    syncFlag:'N'
  }),
  beforeSearch:() => {
    if(query.value.time){
      query.value.createTimeBegin = query.value.time[0]
      query.value.createTimeEnd = query.value.time[1]
    }else{
      delete query.value.createTimeBegin
      delete query.value.createTimeEnd
    }
  }
});
const addRules = {
  trackingNo: [
      { required: true, message: '请输入跟踪号', trigger: 'blur' },
  ]
}
const upFile = ref()
const columns = ref([
  {
    "dataIndex": "trackingNo",
    "title": "跟踪号(快递/卡派)",
    "align": "center",
    "fieldType": "String",
    "type":'input',
  },
  {
    "dataIndex": "deliveryStatus",
    "title": "跟踪状态",
    "align": "center",
    "fieldType": "String",
    "type":'input',
  },
  {
    "dataIndex": "createTime",
    dict:'warehouse_status',
    "title": "创建时间",
    "align": "center",
    "fieldType": "String",
    type:'select',
  },
  {
    "dataIndex": "syncFlag_dictText",
    "title": "是否已处理",
    dict:'warehouse_data_type',
    "align": "center",
    "fieldType": "String",
    "type":'select',
  },
  {
    "dataIndex": "action",
    "title": "操作",
    "align": "center",
  },
])
const checkedList = ref(getLVal('trackList') ? getLVal('trackList') : columns.value.map(item => item.title))
const filterColumns = ref(columns.value.filter(item => checkedList.value.includes(item.title)))
const formItems = ref([
  {
    label:'跟踪号(快递/卡派)',
    type:'input',
    field:'trackingNo',
  },
  {
    label:'跟踪状态',
    type:'select',
    field:'deliveryStatus',
    options: [],
  },
  {
    label:"创建时间",
    type:'rangePicker',
    field: 'time',
    showTime:false
  },
  {
    label:"是否已处理",
    type:'select',
    field: 'syncFlag',
    options: [
      {
        label: '是',
        value:'Y'
      },
      {
        label: '否',
        value:'N'
      }
    ],
  },
])
const editForm = ref(false)
const selectedRowKeys = ref([])
const addForm = ref(false)
const formItem = ref([
  {
    label:"跟踪号",
    value:"trackingNo",
    type:"input"
  },
  {
    label:"跟踪状态",
    value:"deliveryStatus",
    type:"select",
    options:[]
  },
  {
    label:"创建时间",
    value:"createTime",
    type:"date"
  },
])
const addFormItem = ref([
  {
    label:"跟踪号",
    value:"trackingNo",
    type:"input"
  },
  {
    label:"跟踪状态",
    value:"deliveryStatus",
    type:"select",
    options:[]
  },
  {
    label:"创建时间",
    value:"createTime",
    type:"date"
  }
])
const baseData = ref({})
const showDetail = ref(false)
const onSelectChange = (e) => {
  selectedRowKeys.value = e
}
const exportLoading = ref(false);
const importLoading = ref(false);
const openSuperSearch = ref(false)
/**
 * 导出
 * @returns {Promise<void>}
 */
const exports = async () => {
  try{
    exportLoading.value = true;
    let obj = query.value
    if(selectedRowKeys.value.length > 0){
      obj.ids = [...selectedRowKeys.value]
    }
    const res = await postFile('/tms/tracking/status/export','post',obj,'轨迹上传.xlsx')
    message.success('导出成功')
  }catch (e) {
    message.error(e);
  }finally {
    exportLoading.value = false;
  }
}
const cancel = () => {

}
/**
 * 下载模版
 * @returns {Promise<void>}
 */
const downLoadTemplate = async () => {
  try{
    const res = await postFile('/tms/tracking/status/getTemplate','get',{},'轨迹上传模板.xlsx')
  }catch (e) {
    message.error(e)
  }
}
const imports = () => {
  upFile.value.handleShow()
}
/**
 * 删除
 * @param record
 * @returns {Promise<void>}
 */
const handleDel = async (record) => {
  try {
    console.log(record)
    const res = await deleteOne('/tms/tracking/status/delete',{id:record.id})
    message.success('删除成功')
    await search(page.value.pageNo)
  }catch (e){
    message.error(e)
  }
}
/**
 * 初始化字典数据
 * @returns {Promise<void>}
 */
const init = async () => {
  try{
    const res = await getManyDictItems({
      dictCodeList:"sm_status"
    })
    formItems.value[1].options = res.result.sm_status
    formItem.value[1].options = res.result.sm_status
    addFormItem.value[1].options = res.result.sm_status
  }catch (e){
    console.log(e)
  }
}
/**
 * 关闭高级查询
 */
const closeSuperSearch = () => {
  openSuperSearch.value = false
}
const onClearSelected = () => {
  selectedRowKeys.value = []
}

const add = () => {
  addForm.value = true
}
const closeAdd = () => {
  addForm.value = false
}
const handleEdit = (record) => {
  editForm.value = true
  baseData.value = record
}
const closeEdit = () => {
  editForm.value = false
  showDetail.value = false
}
const handleDetail = (record) => {
  editForm.value = true
  baseData.value = record
  showDetail.value = true
}
/**
 * 新增
 * @param form
 * @returns {Promise<void>}
 */
const submitAdd = async (form) => {
  try{
    for (let formKey in form) {
      if(form[formKey] === undefined || form[formKey] === null){
        form[formKey] = ''
      }
    }
    const res = await addTracking(form)
    message.success('新增成功')
    addForm.value = false
    await search(page.value.pageNo)
  }catch (e){
    message.error(e)
  }
}
/**
 * 编辑
 * @param form
 * @returns {Promise<void>}
 */
const submitEdit = async (form) => {
  try{
    for (let formKey in form) {
      if(form[formKey] === undefined || form[formKey] === null){
        form[formKey] = ''
      }
    }
    form.id = baseData.value.id
    const res = await editTracking(form)
    message.success('编辑成功')
    editForm.value = false
    await search(page.value.pageNo)
  }catch (e){
    message.error(e)
  }finally{

  }
}
onMounted(() => {
  init()
})
</script>
<style scoped>

</style>
